#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

// 父子进程进行管道的读写
// 单进程

int main()
{
    int fd[2];
    int len = 0;
    char buffer[100];

    if (pipe(fd) == -1)
    {
        perror("pipe is error\n");
        exit(1);
    }
    int pid = fork();
    if (pid == -1)
    {
        perror("fork is error\n");
        exit(1);
    }
    // 分别关闭父子进程的读端和写端
    if (pid == 0)
    {
        close(fd[1]);
    }
    else
    {
        close(fd[0]);
    }
    // 利用父进程进行写入
    if (pid != 0)
    {
        fgets(buffer, 100, stdin);
        len = strlen(buffer);
        if (len == 0)
        {
            perror("fgets is faile\n");
            exit(1);
        }

        // 写入管道
        if (write(fd[1], buffer, len) != len)
        {
            perror("write is error\n");
            exit(1);
        }
        memset(buffer, 0, sizeof(buffer));
    }
    else
    {
        len = read(fd[0], buffer, 100);
        if (len == -1)
        {
            perror("read is faile\n");
            exit(1);
        }

        if (write(1, buffer, len) != len)
        {
            perror("write is error\n");
            exit(1);
        }
    }

    return 0;
}